export class httpRequest {
  _header: any = {}

  constructor() {
    this._header = {
      'Content-Type': 'application/json',
      'X-AUTHOR': 'shadowee@qq.com'
    }
  }

  getRequest(url: string, data: any, header = this._header) {
    return this.requestAll(url, data, header, 'GET')
  }

  postJson(url: string, data: any, header = this._header) {
    header["Content-Type"] = "application/json";
    return this.requestAll(url, data, header, 'POST')
  }

  postRequest(url: string, data: any, header = this._header) {
    header["Content-Type"] = "application/x-www-form-urlencoded";
    return this.requestAll(url, data, header, 'POST')
  }

  deleteRequest(url: string, data: any, header = this._header) {
    return this.requestAll(url, data, header, 'DELETE')
  }

  putRequest(url: string, data: any, header = this._header) {
    return this.requestAll(url, data, header, 'PUT')
  }

  requestAll(url: string, data: any, header: any, method: 'OPTIONS'
    | 'GET'
    | 'HEAD'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'TRACE'
    | 'CONNECT') {

    // wx.showLoading({ title: "Loading" });
    wx.showNavigationBarLoading({});
    // console.log("正在请求地址及参数:" + url);
    // console.log(data);
    let p = new Promise<any>((resolve, reject) => {
      wx.request({
        url: url,
        data: data,
        header: header,
        method: method,
        success: (res => {
          wx.hideNavigationBarLoading({})
          // wx.hideLoading({})
          // console.log("服务器已响应：statusCode=" + res.statusCode);
          if (res.statusCode === 200) {
            // console.log(res.data);
            let d = res.data;
            resolve(d)
          } else {
            reject(res)
          }
        }),
        fail: (res => {
          wx.hideNavigationBarLoading({});
          wx.hideLoading({})
          console.error(res);
          reject(res)
        })
      })
    })
    return p;
  }
}